<?php
/**
 * Create by 11li
 * Date 2020/1/8
 * Time 10:05
 *
 */

namespace app\common\service;


use app\common\library\Auth;
use app\common\model\Goods;
use app\common\model\GoodsSpec;
use app\common\model\OrderComment;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;

class GoodsService extends BaseService
{
	
	/**
	 * 搜索商品
	 * @param int $page
	 * @param string $keyword
	 * @param string $cateId
	 * @return array
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function searchGoods($page = 1, $keyword = '', $cateId = '')
	{
		$where['status'] = StatusService::STATUS_NORMAL;
		$keyword && $where['goods_name'] = ['like', '%' . $keyword . '%'];
		$cateId && $where['category_id'] = $cateId;
		
		$model = new Goods();
		$total = $model->where($where)->count();
		$list = [];
		
		if ($total > 0) {
			$list = Db::name('goods')->where($where)
				->order(['sort' => 'desc', 'update_time' => 'desc'])
				->page($page)
				->field('id, image, goods_name, price, market_price, sale_number, commission, view_commission')
				->select();
		}
		
		return [
			'total' => $total,
			'list' => $list
		];
	}
	
	public function getGoodsDetail($id)
	{
		try {
			if (!$id || intval($id) <= 0) {
				throw new Exception('参数错误');
			}
			
			$model = new Goods();
			$goods = $model->find($id);
			
			if (!$goods || $goods['status'] != StatusService::STATUS_NORMAL) {
				throw new Exception('商品不存在或已下架');
			}
			
			$goods['banner_images'] = explode(',', $goods['banner_images']);
			
			$specModel = new GoodsSpec();
			$goods['spec_list'] = $specModel->getSpecsByGoodsId($id, StatusService::STATUS_NORMAL);
			
			$goods['comment_number'] = OrderComment::where(['goods_id' => $id, 'status' => StatusService::STATUS_NORMAL])->count();
			
			if($goods['type'] == StatusService::GOODS_TYPE_RESERVATION) {
				$auth = Auth::instance();
				$goods['activity'] = ReservationService::getActivityByGoodsId($id, $auth->id);
			}
			
			return $goods;
			
		} catch (Exception $e) {
			$this->error = $e->getMessage();
			return false;
		}
		
	}
	
	/**
	 * 添加订单商品销量
	 * @param $orderId
	 * @return bool
	 * @throws DataNotFoundException
	 * @throws DbException
	 * @throws ModelNotFoundException
	 */
	public function changeSaleNumber($orderId)
	{
		$goods = Db::name('orderGoods')
			->where('order_id', $orderId)
			->column('number', 'goods_id');
		
		if ($goods) {
			$goodsList = Db::name('goods')
				->where(['id' => ['in', array_keys($goods)]])
				->select();
			
			$data = [];
			foreach ($goodsList as $item) {
				$data[] = [
					'id' => $item['id'],
					'sale_number' => $item['sale_number'] + $goods[$item['id']]
				];
			}
			
			$model = new Goods();
			$res = $model->saveAll($data);
			if(!$res) {
				$this->error = '更改商品销量出错';
				return false;
			}
		}
		return true;
	}
	
	public function getGoodsComment($goodsId, $page = 1)
	{
		if(!$goodsId) {
			throw new Exception('参数错误');
		}
		
		$where =['c.goods_id' => $goodsId, 'c.status' => StatusService::STATUS_NORMAL];
		$count = Db::name('orderComment')->alias('c')
			->where($where)
			->count();
		
		$list = [];
		if($count > 0) {
			$list = Db::name('orderComment')->alias('c')
				->join('user u', 'c.user_id = u.id', 'left')
				->where($where)
				->order(['c.score' => 'DESC', 'c.update_time' => 'DESC'])
				->field('c.content, c.images, c.video_file, c.score, u.nickname, u.avatar')
				->page($page)
				->select();
		}
		
		
		if($list) {
			foreach ($list as &$item) {
				$item['images'] = array_filter(explode(',', $item['images']));
			}
		}
		
		return [
			'list' => $list,
			'total' => $count,
			'page' => $page
		];
	}
	
}